﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Configuration;
using Org.GBarnett.Todo.Dal;

namespace Org.GBarnett.Todo.Bll
{

    /// <summary>
    /// Tasks
    /// </summary>
    public static class Tasks
    {

        private static string _conn = WebConfigurationManager.ConnectionStrings["TodoListConn"].ConnectionString;

        /// <summary>
        /// Returns all the tasks for a particular state.
        /// </summary>
        /// <param name="complete">True to return all complete Tasks, false to return all open Tasks.</param>
        /// <returns>A collection of Task.</returns>
        public static List<Task> GetTasksByState(bool complete)
        {
            using (TodoList db = new TodoList(_conn))
            {
                return (db.Tasks.Where(x => x.Complete == complete).OrderBy(x => x.Title)).ToList<Task>();
            }
        }

        /// <summary>
        /// Updates the state of a task.
        /// </summary>
        /// <param name="taskId">The taskId of the Task to update.</param>
        /// <param name="complete">True if the task is complete, false otherwise.</param>
        public static void UpdateTaskState(int taskId, bool complete)
        {
            using (TodoList db = new TodoList(_conn))
            {
                Task t = db.Tasks.Where(x => x.TaskID == taskId).First();
                t.Complete = complete;
                db.SubmitChanges();
            }
        }

        /// <summary>
        /// Add a new Task.
        /// </summary>
        /// <param name="title">A non-empty string that describes the task.</param>
        /// <param name="complete">True if the task is complete, false otherwise.</param>
        public static void AddTask(string title, bool complete)
        {
            if (string.IsNullOrEmpty(title))
            {
                throw new ArgumentException("Please enter a non-empty string.");
            }
            using (TodoList db = new TodoList(_conn))
            {
                db.Tasks.Add(new Task() { Title = title, Complete = complete });
                db.SubmitChanges();
            }
        }

        /// <summary>
        /// Deletes a task.
        /// </summary>
        /// <param name="taskId">The taskId of the Task to delete.</param>
        public static void DeleteTask(int taskId)
        {
            using (TodoList db = new TodoList(_conn))
            {
                Task t = db.Tasks.Where(x => x.TaskID == taskId).First();
                db.Tasks.Remove(t);
                db.SubmitChanges();
            }
        }

    }
}
